﻿from rest_framework import serializers
from .models import Absent, AbsentType
from apps.oaauth.serializers import UserSerializer
from .utils import get_responder
from .models import AbsentStatusChoices
from rest_framework import exceptions

class AbsentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = AbsentType
        fields = '__all__'


class AbsentSerializer(serializers.ModelSerializer):
    # read_only：这个参数，只会在将DRM模型序列化成字典时会将这个字段序列化
    # write_only：这个参数，只会在将data进行校验的时候才会用到

    # 指向了另一个序列化器(因为AbsentType是另一个类、对象)
    absent_type = AbsentTypeSerializer(read_only=True)
    absent_type_id = serializers.IntegerField(write_only=True)

    # 指向另一个序列化器(requester是用户)
    requester = UserSerializer(read_only=True)
    responder = UserSerializer(read_only=True)

    # 指向序列化器的主要数据(models)
    class Meta:
        model = Absent
        fields = '__all__'

    # 验证absent_type_id是否在数据库中存在
    def validate_absent_type_id(self, value):
        if not AbsentType.objects.filter(pk=value).exists():
            raise exceptions.ValidationError("考勤类型不存在！")
        return value

    # 新增考勤信息的时候使用此函数
    def create(self, validated_data):

        request = self.context['request']
        user = request.user

        # 调用函数获取审批者
        responder = get_responder(request)

        # 如果是董事会的leader，请假就直接通过
        if responder is None:
            validated_data['status'] = AbsentStatusChoices.PASS
        else:
            # 防止前端卡bug，直接令status = 1
            validated_data['status'] = AbsentStatusChoices.AUDITING

        absent = Absent.objects.create(**validated_data, requester=user, responder=responder)
        return absent

    # 修改考勤信息的时候使用此函数
    def update(self, instance, validated_data):
        # 如果不是"审批中"的状态
        if instance.status != AbsentStatusChoices.AUDITING:
            raise exceptions.APIException(detail='不能修改已经确定的请假数据！')

        # 获取请求的用户
        request = self.context['request']
        user = request.user

        if instance.responder.uid != user.uid:
            raise exceptions.AuthenticationFailed(detail='您无权处理该考勤！')

        instance.status = validated_data['status']
        instance.response_content = validated_data['response_content']
        instance.save()

        return instance

